﻿Imports Data

Public Class Cantidades

    Private Sub Cantidades_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try
            Me.CargarLVProductos()
            Me.CargarTipoProducto()
            Me.CargarMarca()

        Catch ex As Exception

        End Try
    End Sub

    Private Function CargarLVProductos() As Boolean
        Try
            Me.lvProducto.Items.Clear()
            Using db As New SerigraphicaDBDataContext

                Dim lista = (From x In db.Stock _
                             Group By x.Tipo_Producto.descripcion, x.Marca.nombre, x.numero_ingreso _
                             Into TOTAL = Sum(x.cantidad_a_entregar), _
                             MULTA = Sum(x.cantidad_MAS), _
                             FAVOR = Sum(x.cantidad_MENOS), _
                             Fecha_Inicial = Min(x.fecha_entrega), _
                             Fecha_Final = Max(x.fecha_entrega), _
                             Minimo = Min(x.id), _
                             Maximo = Max(x.id) _
                             Select descripcion, nombre, TOTAL, MULTA, FAVOR, Fecha_Inicial, Fecha_Final, Minimo, Maximo).ToList

                For Each item In lista
                    lvProducto.Items.Add(New ListViewItem(New String() {item.descripcion, item.nombre, item.TOTAL, item.Fecha_Inicial, item.Fecha_Final}) With {.Name = item.Minimo, _
                                                                                                                                                                .ImageKey = item.Maximo})
                Next

            End Using
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function CargarTipoProducto() As Boolean
        Try
            Using db As New SerigraphicaDBDataContext
                Dim lista As New List(Of AbstractObject)
                lista = db.Tipo_Producto.Select(Function(p) New AbstractObject With {.ID = p.id, .Nombre = p.descripcion}).ToList

                Dim manager As BindingManagerBase = Me.cbxTipoProducto.BindingContext(lista)

                manager.SuspendBinding()
                Me.cbxTipoProducto.DisplayMember = "Nombre"
                Me.cbxTipoProducto.ValueMember = "ID"
                Me.cbxTipoProducto.DataSource = lista
                Me.cbxTipoProducto.Enabled = True
                manager.ResumeBinding()


            End Using
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function CargarMarca() As Boolean
        Try
            Using db As New SerigraphicaDBDataContext
                Dim lista As New List(Of AbstractObject)
                lista = db.Marca.Select(Function(p) New AbstractObject With {.ID = p.id, .Nombre = p.nombre}).ToList

                Dim manager As BindingManagerBase = Me.cbxMarca.BindingContext(lista)

                manager.SuspendBinding()
                Me.cbxMarca.DisplayMember = "Nombre"
                Me.cbxMarca.ValueMember = "ID"
                Me.cbxMarca.DataSource = lista
                Me.cbxMarca.Enabled = True
                manager.ResumeBinding()


            End Using
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function


    Private Sub btnIngresar_Click(sender As System.Object, e As System.EventArgs) Handles btnIngresar.Click
        Try
            If Me.btnIngresar.Text = "Ingresar" Then
                If Me.InsertarStock Then
                    MsgBox("Ingresados Correctamente", MsgBoxStyle.OkOnly, "Confirmacion")
                    If (Me.LimpiarInterfaz()) Then
                        Me.CargarLVProductos()
                    End If

                End If
            Else

            End If
        Catch ex As Exception

        End Try
    End Sub


    Private Function InsertarStock() As Boolean
        Try
            Using db As New SerigraphicaDBDataContext
                Dim desde As Date = Me.dtPickerDesde.Value
                Dim hasta As Date = Me.dtPickerHasta.Value

                Dim añoInicial As Integer = desde.Year
                Dim añoFinal As Integer = hasta.Year

                Dim mesInicial As Integer = desde.Month
                Dim mesFinal As Integer = hasta.Month

                Dim numero = db.Stock.Select(Function(p) p.numero_ingreso).Max
                Dim numero_ingreso As Integer
                If (numero Is Nothing) Then
                    numero_ingreso = 0
                Else
                    numero_ingreso = numero
                End If

                If (añoFinal - añoInicial <> 0) Then
                    Dim cantidadMeses As Integer = (12 - mesInicial) + (0 + mesFinal)
                    Dim cantidadMensual As Double = txtCantidad.Text / (cantidadMeses + 1)

                    For y = 0 To cantidadMeses
                        Dim stock As New Stock
                        stock.id_tipo_producto = cbxTipoProducto.SelectedValue
                        stock.id_marca = cbxMarca.SelectedValue
                        stock.fecha_entrega = desde.AddMonths(y)
                        stock.cantidad_a_entregar = cantidadMensual
                        stock.numero_ingreso = numero_ingreso + 1
                        db.Stock.InsertOnSubmit(stock)
                    Next
                Else
                    Dim division As Integer = mesFinal - mesInicial
                    Dim cantidad As Integer = CInt(txtCantidad.Text)

                    If division = 0 Then
                        Dim stock As New Stock
                        stock.id_tipo_producto = cbxTipoProducto.SelectedValue
                        stock.id_marca = cbxMarca.SelectedValue
                        stock.fecha_entrega = desde
                        stock.cantidad_a_entregar = cantidad
                        stock.numero_ingreso = numero_ingreso + 1
                        db.Stock.InsertOnSubmit(stock)
                    Else
                        For i = 0 To division - 1
                            Dim stock As New Stock
                            stock.id_tipo_producto = cbxTipoProducto.SelectedValue
                            stock.id_marca = cbxMarca.SelectedValue
                            stock.fecha_entrega = desde.AddMonths(i)
                            stock.cantidad_a_entregar = cantidad / division
                            stock.numero_ingreso = numero_ingreso + 1
                            db.Stock.InsertOnSubmit(stock)
                        Next
                    End If

                   
                End If
                db.SubmitChanges()
                Return True
            End Using
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Me.Close()
        Catch ex As Exception

        End Try
    End Sub


    Private Function LimpiarInterfaz() As Boolean
        Try
            Me.txtCantidad.Text = String.Empty
            Me.dtPickerDesde.Value = Date.Now
            Me.dtPickerHasta.Value = Date.Now
            Me.cbxMarca.SelectedValue = 1
            Me.cbxTipoProducto.SelectedValue = 1
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function


    Private Sub IngresarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IngresarToolStripMenuItem.Click
        Try
            If (Me.LimpiarInterfaz) Then
                cbxMarca.Focus()
                Me.btnIngresar.Text = "Ingresar"
            End If
        Catch ex As Exception

        End Try
    End Sub

    
    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarToolStripMenuItem.Click
        Try
            If Me.EliminarStock(Me.lvProducto.SelectedItems(0).Name, Me.lvProducto.SelectedItems(0).ImageKey) Then
                MsgBox("Eliminacion Exitosa", MsgBoxStyle.OkOnly)
                Me.LimpiarInterfaz()
                Me.CargarLVProductos()
            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Function EliminarStock(ByVal r_inicio As Integer, ByVal r_final As Integer) As Boolean
        Try
            Using db As New SerigraphicaDBDataContext
                Dim lista = (From x In db.Stock _
                             Where x.id >= r_inicio And x.id <= r_final _
                             Select x).ToList
                For Each item In lista
                    db.Stock.DeleteOnSubmit(item)
                Next
                db.SubmitChanges()

            End Using
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function
End Class